<template>
    <div class="problem-save">
        <div class="problem-form">
            <el-button type="primary" @click="onSubmit" style="float: right;margin-right: 20px;">{{$t('save')}}</el-button>
            <el-form ref="form" :model="formData" label-width="120px" >
             <el-input v-model="formData.id" v-show="false" disabled></el-input>
            <el-form-item :label="$t('problemMode.save.title')" required style="width: 400px;">
                <el-input v-model="formData.title"></el-input>
            </el-form-item>
            <el-form-item :label="$t('problemMode.save.code')" style="width: 400px;">
                <el-input v-model="formData.code" disabled></el-input>
            </el-form-item>
            <el-form-item :label="$t('problemMode.save.fileId.index')" style="width: 400px;">
                <el-radio-group v-model="formData.type">
                <el-radio :label="0">MarkDown</el-radio>
                <el-radio :label="1">{{$t('problemMode.save.fileId.sec')}}</el-radio>
                </el-radio-group>
            </el-form-item>

            <!-- 上传题目文件 -->
            <el-form-item label="选择题目文件" v-show="formData.type==1" style="width: 490px;">
                <el-button  size="medium" @click="$refs.problemFile.click()">{{problemFileName}}</el-button>
                <!-- <el-input v-model="inputFile" placeholder="请输入内容" type="file" style="width:230px;"></el-input> -->
                <input type="file" ref="problemFile" accept="*" @change="getProblemFile" style="display: none">
                <span style="margin-left: 10px;color: #bfbfbfbf;">文件ID：{{ formData.fileId }}</span>
            </el-form-item>
            <el-form-item :label="$t('problemMode.save.timeLimit')+'(ms)'" prop="timeLimit" style="width: 300px;"
                :rules="[ { required: true, message: '必须为整数'}, { type: 'number', message: '必须为数字'}]">
                <el-input v-model.number="formData.timeLimit" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item :label="$t('problemMode.save.memoryLimit')+'(MB)'" prop="memoryLimit" style="width: 300px;"
                :rules="[ { required: true, message: '必须为整数'}, { type: 'number', message: '必须为数字'}]">
                <el-input v-model.number="formData.memoryLimit" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item :label="$t('problemMode.save.stackLimit')+'(MB)'" prop="stackLimit"  style="width: 300px;"
                :rules="[ { required: true, message: '必须为整数'}, { type: 'number', message: '必须为数字'}]">
                <el-input v-model.number="formData.stackLimit" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item :label="$t('problemMode.save.difficulty')"  style="width: 300px;">
                <el-rate v-model="formData.difficulty"></el-rate>
            </el-form-item>
            <el-form-item :label="$t('problemMode.save.auth.index')"  style="width: 450px;">
                <el-radio-group v-model="formData.auth">
                <el-radio :label="0">{{$t('problemMode.save.auth.fir')}}</el-radio>
                <el-radio :label="1" >{{$t('problemMode.save.auth.sec')}}</el-radio>
                <el-radio :label="2" >{{$t('problemMode.save.auth.thi')}}</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item :label="$t('problemMode.save.mode.index')"  style="width: 400px;">
                <el-radio-group v-model="formData.mode" >
                <el-radio :label="0">{{$t('problemMode.save.mode.fir')}}</el-radio>
                <el-radio :label="1" >{{$t('problemMode.save.mode.sec')}}</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item :label="$t('problemMode.save.spjLanguage')"  style="width: 474px;" v-show="formData.mode==1">
                <el-select v-model="formData.spjLanguage" placeholder="C++/Java/Python" style="width: 120px;">
                <el-option label="C++" value="C++"></el-option>
                <el-option label="Java" value="Java"></el-option>
                <el-option label="Python" value="Python"></el-option>
                </el-select>
              <span style="font-size: 80%;color: #9f9f9f;margin-left: 15px;">注意：程序的输出为交互判题代码的读入</span>
            </el-form-item>
            <el-form-item :label="$t('problemMode.save.spjCode')"  style="width:90%" v-show="formData.mode==1">
                <el-input type="textarea" v-model="formData.spjCode" :autosize="{ minRows: 40, maxRows: 100}" placeholder="输出status状态信息即可（0:答案正确，1：答案错误。）"></el-input>
            </el-form-item>



        </el-form>
        </div>
        <div v-show="formData.type==0">
            <h4 style="text-align: left;margin: 15px;">{{ $t('problemMode.save.desciption') }}</h4>
            <mavonEditor
                ref="md"
                v-model="formData.description"
                v-bind="$attrs"
                v-on="$listeners"
                @imgAdd="handleImgAdd"
                style="min-height: 600px"/>
            <h4 style="text-align: left;margin: 15px;" @click="inputEdit = !inputEdit"><a href="javascript:void(0)">{{ $t('problemMode.save.input') }}</a></h4>
            <mavonEditor :toolbarsFlag = "inputEdit"
                :subfield = 'false'
                ref="md"
                v-model="formData.input"
                v-bind="$attrs"
                v-on="$listeners"
                @imgAdd="handleImgAdd"
                style="min-height: 80px;width: 80%;"/>
            <h4 style="text-align: left;margin: 15px;" @click="outputEdit = !outputEdit"><a href="javascript:void(0)">{{ $t('problemMode.save.output') }}</a></h4>
            <mavonEditor :toolbarsFlag = "outputEdit"
                :subfield = 'false'
                ref="md"
                v-model="formData.output"
                v-bind="$attrs"
                v-on="$listeners"
                @imgAdd="handleImgAdd"
                style="min-height: 80px;width: 80%;"/>
        </div>




        <div style="height:100px"></div>
    </div>

  </template>

  <script>
  /**
   * https://www.npmjs.com/package/mavon-editor
   *
   * npm install mavon-editor --save
   */
  import { mavonEditor } from 'mavon-editor';
  import 'mavon-editor/dist/css/index.css';
  import {uploadImage} from '@/api/admin'
  import * as problemApi from '@/api/problem'
  /**
   *
   * 事件
   * save
   * change
   */
  export default {
    name: '',

    props: [],

    components: {
      mavonEditor,
    },

    data() {
      return {
        formData:{
            type:0,
            timeLimit:1000,
            memoryLimit:512,
            stackLimit:128,
            auth:1,
            mode:0,
        },
        inputEdit:false,
        outputEdit:false,
        problemFileName:"点击上传文件",
        problemFile:null,
        uploadFileFlag:false,  //是否上传过文件
      };
    },

    computed: {},

    methods: {
      //获取题目文件
      getProblemFile(event){
                        // console.info(event.target.files);
          if(event.target.files[0]&&event.target.files[0].name){
            this.problemFile = event.target.files[0];
            this.problemFileName  = event.target.files[0].name;
            this.uploadFileFlag = true;
          }
            // if(event.target.files[1])this.outputFile = event.target.files[1].name;
      },
      // 将图片上传到服务器，返回地址替换到md中
      async handleImgAdd(pos, file) {
        let form = new FormData();
        form.append('file', file);

        const res = await uploadImage(form).then(res=>{
            return '/api/user/download/'+res.data.data;
        })
        console.log(res);
        this.$refs.md.$img2Url(pos, res);
      },
      //提交
      async onSubmit(){
        // console.info(this.formData);
        //题目类型
        if(this.formData.type==1&&this.uploadFileFlag){ //上传的文件
            // if(this.problemFile==null){  //未选择文件
            //     this.$message({type:"warning",message:"未选择文件"})
            //     return ;
            // }
            //获取文件

            let form = new FormData();
            form.append('file', this.problemFile);
            const file_id = await problemApi.uploadProblem(form).then(res=>{
                return res.data.data;
            })
            if(!file_id){
                return ;
            }
            this.formData.fileId = file_id;
            this.problemFile = null;
        }

        if(this.formData.id&&this.$route.query.id){
            problemApi.updateProblem(this.formData).then(res=>{
                if(res.data.success){
                    this.$message({message:"保存成功",type:"success"});
                    this.$router.push({name:"problem"})
                }
            })
        }else{
            problemApi.saveProblem(this.formData).then(res=>{
                if(res.data.success){
                    this.$message({message:"保存成功",type:"success"});
                    this.$router.push({name:"problem"})
                }
            })
        }
      }
    },

    created() {
        if(this.$route.params.id){
            this.formData = this.$route.params;
        }else if(this.$route.query.id){
            // console.info(this.$route.query.id);
            //重新从数据库获取对象
            problemApi.getOneById({"id":this.$route.query.id}).then(res=>{
                if(res.data.code==10000){
                    this.formData = res.data.data;
                }
            })
        }

    },
  };
  </script>

  <style scoped>
  .problem-form{
    margin-top: 20px;
  }

  .problem-save{
  width: 98%;
  background-color: #ffffff;
  border-radius: .1rem;
  overflow-y: auto;
  box-shadow: 2px 2px 2px 2px #afafafaf;
}
  </style>
